为什么我不能使用 splice() 将子字符串插入到数组中?
Why can I not insert a substring into an array using splice()?
请原谅这个小问题,但这真的让我很烦。我正在关注 mozilla 示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
有人可以解释为什么这不起作用:
<body>
<p id="test">
</p>
</body>
var url = "teststring";
document.getElementById("test").innerHTML = (url.split('').splice(2,0,"teststring").join(''));
jsFiddle: https://jsfiddle.net/uyk2p437/1/
生成空字符串的Array#splice
method returns an array containing removed elements, in your case, it would be empty and you are applying Array#join
方法。
改用 String#slice
( or String#substring
) 方法:
url.slice(0, 2) + "teststring" + url.slice(2)
var url = "teststring";
document.getElementById("test").innerHTML = url.slice(0, 2) + "1" + url.slice(2);
<body>
<p id="test">
</p>
</body>
因为拼接的return值是被移除的项目。不是修改后的数组。它就地修改
根据MDN
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
var url = "teststring";
var split = url.split('');
split.splice(2,0,"teststring"); // this returns an empty array because you aren't removing anything
// but the value in split is now:
// ['t','e','t','e','s','t','s','t','r','i','n','g','s','t','s','t','r','i','n','g']
console.log(split.join('')); // gives you the expected result
或者您可以像 Pranav 的回答那样使用 slice
,或者 substr
或 substring
。
请原谅这个小问题,但这真的让我很烦。我正在关注 mozilla 示例:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice 有人可以解释为什么这不起作用:
<body>
<p id="test">
</p>
</body>
var url = "teststring";
document.getElementById("test").innerHTML = (url.split('').splice(2,0,"teststring").join(''));
jsFiddle: https://jsfiddle.net/uyk2p437/1/
生成空字符串的Array#splice
method returns an array containing removed elements, in your case, it would be empty and you are applying Array#join
方法。
改用 String#slice
( or String#substring
) 方法:
url.slice(0, 2) + "teststring" + url.slice(2)
var url = "teststring";
document.getElementById("test").innerHTML = url.slice(0, 2) + "1" + url.slice(2);
<body>
<p id="test">
</p>
</body>
因为拼接的return值是被移除的项目。不是修改后的数组。它就地修改
根据MDN
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
var url = "teststring";
var split = url.split('');
split.splice(2,0,"teststring"); // this returns an empty array because you aren't removing anything
// but the value in split is now:
// ['t','e','t','e','s','t','s','t','r','i','n','g','s','t','s','t','r','i','n','g']
console.log(split.join('')); // gives you the expected result
或者您可以像 Pranav 的回答那样使用 slice
,或者 substr
或 substring
。