简体   繁体   English

为什么调用split和splice给出空数组?

[英]why calling split and splice gives empty array?

In this JavaScript, why don't i get azbc ? 在这个JavaScript中,为什么我不能获得azbc

var x = "a-b-c".split('-').splice(1, 0, 'z');
alert(x.join(''));

split returns an array containing a , b and c . split返回一个包含abc的数组。

Shouldn't splice insert z after a and gives me azbc ? 不应splice插入za ,给我azbc

Why do i get an empty array? 为什么我得到一个空数组?

note: i know that what i want can be accomplished by: 注意:我知道我想要的东西可以通过以下方式完成:

var x = "a-b-c".split('-')
x.splice(1, 0, 'z');
alert(x.join(''));

since splice "modifies" the original array itself. 因为splice “修改”原始数组本身。 shouldn't it modify {a,b,c} to {a,z,b,c} and then be assigned to x ? 不应该将{a,b,c}修改为{a,z,b,c} ,然后将其分配给x

got it... the code below helped me to understand. 得到它......下面的代码帮助我理解。

var x = "a-b-c".split('-')
x = x.splice(1, 0, 'z');
alert(x.join(''));

splice returns the removed items from the array, not the new array: splice从数组中返回已删除的项,而不是新数组:

> x = 'a-b-c'.split('-');
["a", "b", "c"]
> x.splice(1,0,'z');
[]
> x
["a", "z", "b", "c"]
> x.splice(1,1,'x');
["z"]
> x
["a", "x", "b", "c"]

Like Paolo said, splice modifies the array in place http://jsfiddle.net/k9tMW/ 像Paolo说的那样,splice修改了数组到位http://jsfiddle.net/k9tMW/

var array = "a-b-c".split('-');
array.splice(1, 0, 'z');
alert(array.join(''));

Mozilla Developer Network-Array splice method - Changes the content of an array, adding new elements while removing old elements. Mozilla Developer Network-Array拼接方法 - 更改数组的内容,在删除旧元素时添加新元素。

Returns - An array containing the removed elements. 返回 - 包含已删除元素的数组。 If only one element is removed, an array of one element is returned. 如果仅删除一个元素,则返回一个元素的数组。

var x = "a-b-c".split('-');
x.splice(1, 0, 'z');
document.write(x + "<br />"); 

You have to do like this, 你必须这样做,

var x = "a-b-c".split('-');
x.splice(1, 0, 'z');
alert(x.join(''));​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM