我有這個陣列length = 3:
state = ["q0", "q1", "q2,q3"]
我想修改它,我希望它看起來像這樣:
state = ["q0", "q1", "q2", "q3"] // length = 4.
我想以string = "q2,q3"一種我將得到的方式剪切"q2","q3"以便我可以用 替換該state[2]值"q2"并自動添加到陣列中,例如state[3] = "q3".
有誰知道我該怎么做?
我嘗試了該split方法,但它沒有按我的意愿作業。
uj5u.com熱心網友回復:
flatMap 非常適合這個。
["q0", "q1", "q2,q3"].flatMap(v => v.split(','))
flatMap 映射然后變平。所以使用 split 映射給你[['q0'], ['q1'], ['q2', 'q3']],然后展平展開每個二級陣列。
uj5u.com熱心網友回復:
我會迭代state,嘗試拆分每個值,然后將它們推送到 res 陣列。
const state = ["q0", "q1", "q2,q3"];
const res = [];
state.forEach((value) => {
const splitValue = value.split(",");
res.push(...splitValue);
});
uj5u.com熱心網友回復:
let state = ["q0", "q1", "q2,q3"];
state=state.join(',');
state=state.split(',');
console.log(state);
uj5u.com熱心網友回復:
您好,我舉了一個例子,獲取最后一個索引中的間隙并將其拆分
let deneme = ["first","second","third fourth"];
let index = deneme[2].indexOf(" "); // Gets the first index where a space occours
let firstPart = deneme[2].slice(0, index); // Gets the first part
let secondPart = deneme[2].slice(index 1);
console.log("first try" ,deneme);
deneme[2] = firstPart;
deneme.push(secondPart);
console.log("second look",deneme);
uj5u.com熱心網友回復:
您可以使用三種 javascript 方法來完成。forEach(), concat(), 和split(). 一個班輪
let result = []
state.forEach(a => result = result.concat(a.split(",")))
uj5u.com熱心網友回復:
實作這一目標的一種簡單且坦率地說是幼稚的方法:
// initial state, chained immediately to
// Array.prototype.map() to create a new Array
// based on the initial state (["q0", "q1", "q2, q3"]):
let state = ["q0", "q1", "q2, q3"].map(
// str is a reference to the current String of the Array
// (the variable name is free to be changed to anything
// of your preference):
(str) => {
// here we create a new Array using String.prototype.split(','),
// which splits the string on each ',' character:
let subunits = str.split(',');
// if subunits exists, and has a length greater than 1,
// we return a new Array which is formed by calling
// Array.prototype.map() - again - and iterating over
// each Array-element to remove leading/trailing white-
// space with String.prototype.trim(); otherwise
// if the str is either not an Array, or the length is
// not greater than 1, we return str:
return subunits && subunits.length > 1 ? subunits.map((el) => el.trim()) : str;
// we then call Array.prototype.map():
}).flat();
// and log the output:
console.log(state);
參考:
Array.prototype.flat().Array.prototype.map().- 條件(“三元”)運算子。
- `String.prototype.split()。
String.prototype.trim().
uj5u.com熱心網友回復:
根據@TrevorDixon 的解決方案,Array#flatMap是要走的路。如果您有多個分隔符,您可以使用正則運算式,String#split如以下演示所示:
const
input = ["q0", "q1", "q2,q3","q4 q5| q6"],
output = input.flatMap(v => v.split(/[ ,|] /));
console.log( output );
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/531060.html
上一篇:檢查陣列中的單個連續字符
