最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Spread Operator Issue with Float and Boolean Variable - Stack Overflow

programmeradmin6浏览0评论

Spread Operator throws error for float and boolean variable. Is there any specific reason for getting error on float and boolean variable.

// Works, Array Variable
'use strict';

let aVal = [1, 2, 3];
console.log(...aVal);

// Works, String Variable
'use strict';

let sVal = 'String';
console.log(...sVal);

// throws error, Integer Variable
'use strict';

let iVal = 1234567890;
console.log(...iVal);

// throws error, Float Variable
'use strict';

let fVal = 99.45;
console.log(...fVal);

// throws error, Boolean Variable
'use strict';

let bVal = true;
console.log(...bVal);

Spread Operator throws error for float and boolean variable. Is there any specific reason for getting error on float and boolean variable.

// Works, Array Variable
'use strict';

let aVal = [1, 2, 3];
console.log(...aVal);

// Works, String Variable
'use strict';

let sVal = 'String';
console.log(...sVal);

// throws error, Integer Variable
'use strict';

let iVal = 1234567890;
console.log(...iVal);

// throws error, Float Variable
'use strict';

let fVal = 99.45;
console.log(...fVal);

// throws error, Boolean Variable
'use strict';

let bVal = true;
console.log(...bVal);
Share Improve this question edited Aug 9, 2016 at 16:19 Venkat.R asked Aug 9, 2016 at 11:34 Venkat.RVenkat.R 7,7765 gold badges44 silver badges68 bronze badges 1
  • 4 Yes, because you can't iterate over them. What result would you expect from spreading a float for example? – Thomas Commented Aug 9, 2016 at 11:45
Add a ment  | 

1 Answer 1

Reset to default 8

Is there any specific reason for getting error on float and boolean variable.

Yes: Spread syntax (it isn't an operator) only works with iterable objects (objects that implement iteration). Numbers and booleans are not iterable. Things like arrays and maps and sets are iterable.

console.log(...aVal); asks the JavaScript engine to iterate through aVal and then call console.log with each iterated value as a discrete argument. That is, it asks javaScript to "spread out" that iterable.

Here's an example of spread with an iterable (in this case, an array):

function foo(a, b, c, d) {
  console.log(a);
  console.log(b);
  console.log(c);
  console.log(d);
}
let a = ["the", "answer", "is", 42];
foo(...a);

Note how the entries in a are "spread out" into discrete (separate) arguments for foo.


The examples below were from earlier when your question was asking about "the rest operator" by mistake. Just for pleteness:

Here's an example of rest syntax (also not an operator) in a function signature:

function foo(...args) {
  console.log(`I got ${args.length} args`);
}
foo('a', 'b', 'c');

...and rest syntax in a destructuring assignment:

let a = ['a', 'b', 'c', 'd', 'e'];
let [ x, y, ...z ] = a;
console.log(x);
console.log(y);
console.log(z);

发布评论

评论列表(0)

  1. 暂无评论