How to replace all undefined values in an array with “-”?

核能气质少年 提交于 2020-01-24 19:46:31

问题


I have an array like:

var array = [1, 2, undefined, undefined, 7, undefined]

and need to replace all undefined values with "-". The result should be:

var resultArray = [1, 2, "-", "-", 7, "-"]

I think there is a simple solution, but I couldn't find one.


回答1:


You could check for undefined and take '-', otherwise the value and use Array#map for getting a new array.

var array = [1, 2, undefined, undefined, 7, undefined],
    result = array.map(v => v === undefined ? '-' : v);
    
console.log(result);

For a sparse array, you need to iterate all indices and check the values.

var array = [1, 2, , , 7, ,],
    result = Array.from(array, v => v === undefined ? '-' : v);
    
console.log(result);



回答2:


You can use Array.map

var array = [1, 2, undefined, undefined, 7, undefined];
var newArray = array.map(x => x !== undefined ? x : "-");
console.log(newArray);



回答3:


You can map the values and return - if undefined.

let array = [1, 2, undefined, undefined, 7, undefined]

let result = array.map(o => o !== undefined ? o : '-');

console.log(result);



回答4:


Use Array.map()

var array = [1, 2, undefined, undefined, 7, undefined];
console.log(array);

var newArray = array.map(function(v) {
  return undefined === v ? '-' : v;
});

console.log(newArray);



回答5:


var newArray = array.map(function(val) {
    if (typeof val === 'undefined') {
        return '-';
    }
    return val;
});



回答6:


Try using this -

array.forEach(function(part,index,Arr){ if(!Arr[index])Arr[index]='-'})



回答7:


 function SampleArray() {
            var Array = [];
            var array = [1, 2, undefined, undefined, 7, undefined];
            for (var i = 0; array.length > i; i++) {
                var Value;
                if (array[i] == undefined) {
                    Value = '-';
                } else {
                    Value = array[i];
                }

                Array.push(Value);
            }
        }



回答8:


You can use functional programming map function:

 let array = [1, 2, undefined, undefined, 7, undefined];

 let array2 = array.map(e => e === undefined ?  e='-' :  e);



回答9:


Try:

while((index = array.indexOf(undefined)) > -1){array[index] = "-";}

"-"

this will search for the index of the value you are searching for, and replace it with "-"



来源:https://stackoverflow.com/questions/49853647/how-to-replace-all-undefined-values-in-an-array-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!