如果不是空的,则在数组元素上使用Substr

时间:2016-07-12 23:07:27

标签: javascript arrays substr

嘿,我有一个包含一些空字符串的数组和一些包含内容的字符串。

我想要切掉那些非空字符串的前5个字母,并将它们放入一个新数组中。我也想保留空的。

示例:

myArray = [ "","","123456789","","",""];
var newArray = ["","","12345","","",""]

我尝试使用for循环,如果myArray [i]为空,则不要执行substr(),但是我得到一个错误,它不是函数。

我实际上并不需要将它放入一个新的数组中,我只想将myArray(i).subsrt(5)值放入splice()中,但后来我得到了错误:

  

VM750:82未捕获的TypeError:无法读取属性' substr'未定义的

4 个答案:

答案 0 :(得分:1)

如果没有看到所有代码,很难知道你的确切问题是什么,但是这里有一个for循环遍历第一个数组中的所有元素并且每个字符串的前5个或更少字符插入新数组。

myArray = [ "","","123456789","","",""];
var newArray = [];
for(var i = 0; i < myArray.length; i++) {
    newArray.push(myArray[i].substr(0,5));
} 

答案 1 :(得分:1)

ES6与array.map

myArray = [ "","","123456789","","",""];
var newArray = myArray.map((s) => s.substr(0, 5))

答案 2 :(得分:1)

正是@le_m所说的:

myArray = [ "","","123456789","","",""];
var newArray = myArray.map(e => e.substr(0, 5));

答案 3 :(得分:0)

您需要将substr用于非空项目:
像这样:

myArray = [ "","","123456789","","",""];
for(var i = 0; i < myArray.length; i++) {
    temp = myArray[i];
    if (temp && temp != "")
      myArray[i] = temp.substr(0, 5);
    else
      myArray[i] = "";
}