简体   繁体   中英

Replace multiple string items in the array

I have an array that shows this value "135_1,undefined,undefined"

I have to find the "undefined" in the above array and then replace it with "0_0".Undefined can occur multiple times in the array.

I used

 var extra = myVariable.replace("undefined", "0_0");
    alert(extra);

but then I have to use this three times so that every single time it can search one and replace it.

I have also used this::

  for (var i = 0; i < myVariable.length; i++) {
        alert(myVariable[i]);
        myVariable[i] = myVariable[i].replace(/undefined/g, '0_0');
    }
    alert(myVariable);

but it did'nt solved my purpose.

String.prototype.replace is a method accessible to strings. undefined is not a string.

This might help you.

for (var i=0, len=arr.length; i<len; i++) {
  if (arr[i] === undefined) {
    arr[i] = "0_0";
  }
}

alert(JSON.stringify(arr));

You could also use Array.prototype.map for this. Note, it only works in IE >= 9

arr = arr.map(function(elem) {
  return elem === undefined ? "0_0" : elem;
});

Since the question is tagged with you can use $.map() :

var extra = $.map(myVariable, function(item) {
    return item || '0_0';
}

This will return a new array whereby each item comprising (in your case) an empty string or undefined is replaced by '0_0' .

var arr = ['135_1',undefined,undefined];
while(arr.indexOf(undefined) != -1) {
    pos=arr.indexOf(undefined);
    arr[pos]='0_0';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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