我正在尝试搜索将句子分成单词或更小句子的内容。我不知道如何准确理解,但我可以举例说明。
假设我有句The quick brown fox jumps over the lazy dog
我想在json数组中这样做
["The","The quick","The quick brown","The quick brown fox","The quick brown fox jumps","The quick brown fox jumps over","The quick brown fox jumps over the","The quick brown fox jumps over the lazy","The quick brown fox jumps over the lazy dog"]
我不知道如何用技术术语解释它,但我希望我已经给出了适当的例子
更新1:
我很抱歉这个小提琴只是在我的脑海中点击,我希望得到不同的结果。例句It is my dream
预期结果["It", "It is", "It is my", "It is my dream","is", "is my", "is my dream", "my", "my dream"]
答案 0 :(得分:6)
正如@Leguest所述,JSON数组以[]
括号开头和结尾,所以应该这样:
["The","The quick","The quick brown","The quick brown fox","The quick brown fox jumps","The quick brown fox jumps over","The quick brown fox jumps over the","The quick brown fox jumps over the lazy","The quick brown fox jumps over the lazy dog"]
我可以想办法做到这一点。简单地拆分和循环:
var phrase = "The quick brown fox jumps over the lazy dog".split(" ");
var arr = [];
var str = "";
for (var i = 0; i < phrase.length; i++) {
str += phrase[i] + " ";
arr.push(str.trim());
}
console.log("Array:", arr);
console.log("Array string:", JSON.stringify(arr));
&#13;
请注意,对于可读性摇晃,这不符合要求(在添加的每个单词上执行trim
)。如果你想要一种高效的方法,你就可以做到这一点(只需要很小的改动来检测第一个单词):
var phrase = "The quick brown fox jumps over the lazy dog".split(" ");
var arr = [];
var str = "";
for (var i = 0; i < phrase.length; i++) {
if (i > 0) {
str += " ";
}
str += phrase[i];
arr.push(str);
}
console.log("Array:", arr);
console.log("Array string:", JSON.stringify(arr));
&#13;
答案 1 :(得分:4)
如果您想要一个不涉及迭代的答案,这可能就是您所需要的:
function getresult(total, current) {
total.length != 0 ? total.push(total[total.length-1].split(" ").concat([current]).join(" ")) : total.push(current);
return total;
}
var data = "The quick brown fox jumps over the lazy dog";
var dataArr = data.split(" ");
var results = dataArr.reduce(getresult, []);
console.log(results);
reduce方法在数组元素(dataArr)上应用函数(在本例中为getresult)。 所需的函数将在累加器参数(将是最后一次迭代的结果)和下一个元素上运行。 对于第一次迭代,我们需要一个初始值,这是第二个参数(空数组)
为了向数组添加新元素,我们使用concat,它返回一个新数组,因此我们保持不变性。
答案 2 :(得分:1)
string = "Hello how are you my dear?";
function get(string) {
var ret = [];
var data = string.split(" ");
var s = "";
for(var i = 0; i < data.length;i++) {
s += data[i] + " ";
ret.push(s.replace(data[i] + " ",data[i]));
}
return ret;
}
-UPDATE
string = "Hello how are you my dear?";
function get(string,count =0) {
var ret = [];
var data = string.split(" ");
var s = "";
for(var i = count;i < data.length;i++) {
s += data[i] + " ";
ret.push(s.replace(data[i] + " ",data[i]));
}
return ret;
}
我为你想要的东西添加了计数,所以你可以这样做:
get(string,1);
get(string,2);
get(string,3);
get(string,4);
预期产出:
["how", "how are", "how are you", "how are you my", "how are you my dear?"]
["are", "are you", "are you my", "are you my dear?"]
["you", "you my", "you my dear?"]
["my", "my dear?"]