我正在尝试将push
数据放在array
的确切位置,但我得到的结果是错误的......
任何人都告诉我这样做的正确方法吗?
我的代码:
var ar = ['one','two','three'];
ar[5] = 'five';
ar.join();
console.log(ar); //result ["one", "two", "three", 5: "five"]
我看的结果是:
["one", "two", "three", "", "", "five"]
更新 Live
答案 0 :(得分:1)
ar.join()
不会更改ar
。只要您的数据中没有管道(|),这应该可以完成您正在寻找的内容:
console.clear();
var ar = ['one','two','three'];
ar[5] = 'five';
console.log(ar); //["one", "two", "three", 5: "five"]
ar= ar.join('|').split('|');
console.log(ar); //["one", "two", "three", "", "", "five"]

答案 1 :(得分:0)
行为是正确的。你所做的相当于:
a = ["one", "two", "three", undefined, undefined, "five"]
浏览器显示它的方式与Chrome的控制台不同,后者显示:
["one", "two", "three", undefined × 2, "five"]
如果你想在'洞'中留空字符串,你必须自己把它们放在那里,例如:
var a = ["one", "two", "three"];
a[3] = a[4] = "";
a[5] = "five";
是的,请注意"one"
位于索引0,而不是索引1.