基于另一个数组修改数组 JavaScript
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/11 18:20:17
假设,我们有一个像这样的短语引用数组 −
const reference = ["your", "majesty", "they", "are", "ready"];
并且我们需要基于另一个数组连接上述数组的一些元素,因此如果另一个数组是这个 −
const another = ["your", "they are"];
结果将类似于 −
result = ["your", "majesty", "they are", "ready"];
在这里,我们比较了两个数组中的元素,如果第一个数组中的元素在第二个数组中同时存在,我们将第一个数组中的元素连接起来。
我们需要编写一个 JavaScript 函数,该函数接受两个这样的数组并返回一个新的连接数组。
示例
const reference = ["your", "majesty", "they", "are", "ready"];
const another = ["your", "they are"];
const joinByReference = (reference = [], another = []) => {
const res = [];
const filtered = another.filter(a => a.split(" ").length > 1);
while(filtered.length) {
let anoWords = filtered.shift();
let len = anoWords.split(" ").length;
while(reference.length>len) {
let refWords = reference.slice(0,len).join(" ");
if (refWords == anoWords) {
res.push(refWords);
reference = reference.slice(len,reference.length);
break;
};
res.push(reference.shift());
};
};
return [...res, ...reference];
};
console.log(joinByReference(reference, another));
输出
这将产生以下输出 −
[ 'your', 'majesty', 'they are', 'ready' ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

