除了(1)项目外,如何输出数组作为场景?我们假设数组的内容是:["!report","Jay","This","is","the","reason"];
我尝试在(1)之后输出项目:(args.slice(1));
但是输出现在是:"这是,原因",我怎么能把它输出为普通的风格?
答案 0 :(得分:3)
如果您不想使用内置方法,可以附加每个单词 在从索引1开始的数组中(第二项)。
// List of words
var words = ["!report","Jay","This","is","the","reason"];
// Empty string
var sentence = "";
// Loop through array starting at index 1 (second item)
for (let i = 1; i < words.length; i++) {
// Keep appending the words to sentence string
sentence = sentence + words[i] + " ";
}
// Print the sentence as a whole
console.log(sentence);
或使用内置功能:
// Array of strings
var array = ["!report","Jay","This","is","the","reason"];
// Cut off the first element, words is still an array though
var words = array.slice(1)
// Join each element into a string with spaces in between
var sentence = words.join(" ")
// Print as full sentence
console.log(sentence)
输出:
"Jay This is the reason"
答案 1 :(得分:0)
.slice()
会返回一个新数组,因此当您整体访问它时,您经常会看到以逗号分隔的数组值列表。
但是,.slice()
以及 .join()
可以解决问题。 .join()
允许您加入&#34;所有数组值都作为单个字符串。如果将参数传递给.join()
,则该参数将用作分隔符。
然后,您可以将句点(.
)连接到字符串的末尾。
console.log(["!report","Jay","This","is","the","reason"].slice(1).join(" ") + ".");
&#13;
答案 2 :(得分:0)
您可以从第二个元素切片并加入数组。
{{1}}
答案 3 :(得分:0)
您想要的输出不是很清楚(您只想删除第一项还是第二项)。但是方法是一样的:
如果您符合es6标准,则可以使用destructuring assignment syntax
const arr = [a,b,...c] = ["!report","Jay","This","is","the","reason"];
let sentence = c.join(" ");
// or
let sentence2 = c.toString().replace(/,/g," ");
console.log (sentence," - ",sentence2);
或简单地用正则表达式和正确的模式替换
const arr = ["!report","Jay","This","is","the","reason"];
let sentence = arr.toString().replace(/^[A-z! ]+?,[A-z ]+?,/,"").replace(/,/g," ");
// or
let sentence2 = arr.toString().replace(/^[A-z! ]+?,/,"").replace(/,/g," ");
console.log (sentence," - ",sentence2);
答案 4 :(得分:-1)
在这里,检查代码说明的小提琴注释。
var a = ["!report","Jay","This","is","the","reason"];
//removes first element from array and implodes array with spaces
var sentence = a.slice(1).join(" ");
console.log(sentence);
&#13;