好的,所以我有這個函式,它假設將它在字串中找到的特定單詞記錄到控制臺中。但它有點......是的,它不起作用。
function foo(input) {
for (var i = 0; i < input.length; i ) {
const character = input[i]
// To make sure it doesnt always get
// the very first blank space I do the following \/ (I think this is the trouble area)
const word = input.substring(i, input.substring(i, input.length).indexOf(' '))
console.log(word)
if (word == "foo bar") {
console.log(word)
console.log("worked!") // <- currently does not fire
// word should only print "foo bar" without linebreaks
}
}
}
foo(" foo bar ");
我什至不知道如何解釋正在發生的事情。但我相信這個可怕的影像會給你一個想法。

預期的輸出,上面或下面有一些換行符,是:
“f”
“fo”
“foo”
“foo”
“foo b”
“foo ba”
“foo bar”
“作業!”
還要記住,無論有沒有換行符,這都不起作用(我同時測驗了兩者),我希望它同時適用于兩者。
例子:
// single line (does not work)
foo(" foo bar ")
// line breaks (does not work)
foo(`
foo bar
`)
uj5u.com熱心網友回復:
在 for 回圈之外定義word...并在每次迭代時將當前字符添加到其中。
const input = "foo bar"
function foo(input) {
let word = "" // Define it out of the loop
for (var i = 0; i < input.length; i ) {
const character = input[i]
word = character // add the current loop character here
console.log(word)
if (word == "foo bar") {
console.log("worked!") // <- is firing now
}
}
}
foo(input)
來自評論:
如果我有字串“這是一個 foo bar lalalalala”,我只想得到“foo bar”部分。
然后使用match將是一種方式。
const input = "This is a foo bar lalalalala"
function foo(input) {
let match = input.match(/foo bar/)
if (match) {
console.log("worked!") // <- is firing now
}
}
foo(input)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/459505.html
標籤:javascript
