tki*_*m90 15 javascript function
I can't quite understand why the join() call below produces different results, depending on the type of argument(s) provided.
Here's what I found:
var test = function() {
var args = Array.prototype.join.call(arguments,"_");
return args
};
console.log(test([1,2,3])) // #1: returns 1,2,3
console.log(test(1,2,3)) // #2: returns 1_2_3Run Code Online (Sandbox Code Playgroud)
Given join(arguments, '_'), shouldn't it produce a _ delimited string in both tests above? Why does #1 return a comma delimited value instead?
Cer*_*nce 12
When you pass an array to test, the arguments object becomes an array of arrays, not a plain array of plain values. It's the difference between
arguments = [[1,2,3]];
Run Code Online (Sandbox Code Playgroud)
and
arguments = [1,2,3];
Run Code Online (Sandbox Code Playgroud)
When you call .join on an array of arrays, each inner array gets implicitly coerced to a string first, resulting in '1,2,3' - the values of the inner arrays do not get .joined by the delimiter, only the immediate children of the outer array get .joined by the delimiter.
In your code, you only have one argument in the first example, that being an array. Joining a single element will remove the brackets:
var test = function() {
var args = Array.prototype.join.call(arguments,"_");
return args
};
console.log(test([1,2,3])) // args = [[1,2,3]]
console.log(test(1,2,3)) // args = [1,2,3]
console.log([[1,2,3]].join('_'))
console.log([1,2,3].join('_'))Run Code Online (Sandbox Code Playgroud)
Another way to look at this is to provide another array as an argument to test():
var test = function() {
var args = Array.prototype.join.call(arguments,"_");
return args
};
console.log(test([1,2,3], [4,5,6]))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
882 次 |
| 最近记录: |