我想将数组值分配给 DOM 中的属性:
var myArray = [1, 2, 3];
elem.setAttribute('value', myArray)
在现代浏览器中你会得到这样的结果:
<input value="1,2,3">
但在较旧的版本中(最高为 IE9):
<input value="[object]">
JSON.stringify
不是解决方案,因为这会生成:
<input value="[1,2,3]">
问题是 myArray.toString()
在现代浏览器中输出:
1,2,3
在年长的时候:
[object]
我该如何解决这个问题?
最佳答案
如果您打算使用 toString
方法,您可以像这样覆盖它:
var myArray = [1, 2, 3];
Array.prototype.toString = function () {
return this.join(', ');
}
console.log(myArray.toString()); //1, 2, 3
这应该适用于大多数旧版浏览器。
关于javascript - 如何使 IE9 中的 Array.toString() 兼容现代浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19629776/