gpt4 book ai didi

Javascript 数组 valueOf 方法

转载 作者:数据小太阳 更新时间:2023-10-29 06:12:11 24 4
gpt4 key购买 nike

[].valueOf() 方法返回数组本身。根据这个

document.write([["a"]],["b"]) 

应该返回 ['a']b 不是吗?但这并没有发生,它只是写了 ab。我只是想知道这背后的原因。

对于字符串元素 .toString() 方法返回这个,

["a","b"].toString()//a,b

但是对于带有数组的元素,它应该返回

[["a"],"b"].toString()//[a],b

最佳答案

当您将对象传递给 document.write 时,Javascript 会使用 .toString() 将对象转换为字符串。在这种情况下,Array.toString()将展平并用逗号连接数组,并将其作为字符串返回。

["this", "is", "an", "array!"].toString(); // "this,is,an,array!"
[["a",["b"]], ["c"]].toString() // "a,b,c"

我们可以将 document.write([["a",["b"]], ["c"]]) 展开为以下内容:

var input = [["a",["b"]], ["c"], "d"];
Array.prototype.verboseToString = function verboseToString() {
// Make a copy of the array, so we don't destroy the original
var copy = this.slice(), i;
for (i = 0; i < copy.length; i++) {
// If this is an Array, call verboseToString() on it, and go deeper
if (copy[i] instanceof Array === true) {
copy[i] = copy[i].verboseToString();
}
}
// copy contains non-arrays and we're ignoring other types' toString() output
return copy.join(',');
}
document.write(input.verboseToString()); // "a,b,c,d"

关于Javascript 数组 valueOf 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17247122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com