将数字字符串替换为数组中的数字
replace numeric string to number inside an array
我想从
转换一个数组
arr = ["step","0","instruction","1"]
至
newArr = ["step",0,"instruction",1]
这是我的示例代码:
newArr = arr.map((x) => {
if (typeof x === "number") {
return x;
}
});
在这种情况下,您可以检查字符串是否可转换为有限数字并映射数字。
const
data = ["step", "0", "instruction", "1"],
result = data.map(v => isFinite(v) ? +v : v);
console.log(result);
如果您还需要所有其他数字,您可以转换为数字并检查字符串是否与值相符。
const
data = ["step", "0", "instruction", "1", "NaN", "Infinity"],
result = data.map(v => v === (+v).toString() ? +v : v);
console.log(result);
我想你正在寻找这样的东西:
// Defining initial values
const initialValues = ["step","0","instruction","1"]
// Mapping initial values to a new parsed array
const parsedValues = initialValues.map(value => {
// We try to parse the value. If it isNaN (Not a number) we just return the value e.g. don't change it
if(isNaN(parseInt(value))) return value;
// Else the value can be parsed to a number, so we return the parsed version.
return parseInt(value);
})
// Printing the parsed results
console.log(parsedValues);
试试这个:
const arr = ["step","0","instruction","1"]
const newArray = arr.map(value => { //Iterate the array searching for possible numbers.
/* Check with function isNaN if the value is a number,
if true just return the value converted to number,
otherwise just return the value without modification */
if (!Number.isNaN(Number(value))) {
return Number(value)
}
return value
})
我想从
转换一个数组arr = ["step","0","instruction","1"]
至
newArr = ["step",0,"instruction",1]
这是我的示例代码:
newArr = arr.map((x) => {
if (typeof x === "number") {
return x;
}
});
在这种情况下,您可以检查字符串是否可转换为有限数字并映射数字。
const
data = ["step", "0", "instruction", "1"],
result = data.map(v => isFinite(v) ? +v : v);
console.log(result);
如果您还需要所有其他数字,您可以转换为数字并检查字符串是否与值相符。
const
data = ["step", "0", "instruction", "1", "NaN", "Infinity"],
result = data.map(v => v === (+v).toString() ? +v : v);
console.log(result);
我想你正在寻找这样的东西:
// Defining initial values
const initialValues = ["step","0","instruction","1"]
// Mapping initial values to a new parsed array
const parsedValues = initialValues.map(value => {
// We try to parse the value. If it isNaN (Not a number) we just return the value e.g. don't change it
if(isNaN(parseInt(value))) return value;
// Else the value can be parsed to a number, so we return the parsed version.
return parseInt(value);
})
// Printing the parsed results
console.log(parsedValues);
试试这个:
const arr = ["step","0","instruction","1"]
const newArray = arr.map(value => { //Iterate the array searching for possible numbers.
/* Check with function isNaN if the value is a number,
if true just return the value converted to number,
otherwise just return the value without modification */
if (!Number.isNaN(Number(value))) {
return Number(value)
}
return value
})