gpt4 book ai didi

javascript - Eloquent Javascript 中的练习 4.4 -- startsWith() 和 .slice

转载 作者:行者123 更新时间:2023-11-30 08:43:21 24 4
gpt4 key购买 nike

我正在用 Eloquent JavaScript 做练习 4.4。

问题是:

Write a function called startsWith that takes two arguments, both strings. It returns true when the first argument starts with the characters in the second argument, and false otherwise.

这是我想出的解决方案:

JSFiddle:http://jsfiddle.net/ErhKS/3/

function startsWith(string1, pattern) {
if (string1.slice(0,4) === pattern.slice(0,4) {
return true;
}
}

console.log(startsWith("something", "somethingmore"));

我不明白为什么我在 console.log() 中收到错误。

我确实理解这本书的解决方案,以及为什么它是一个好的解决方案:

function startsWith(string, pattern) {
return string.slice(0, pattern.length) == pattern;
}

我只是想知道为什么我自己写得不好的函数在控制台中出错并返回:

Uncaught SyntaxError: Unexpected token { .

最佳答案

这是因为您还没有结束您的 if 语句中的所有括号。

function startsWith(string1, pattern) {
if (string1.slice(0,4)) === pattern.slice(0,4) {
return true;
}
}

这是一个有效的更新示例:http://jsfiddle.net/ErhKS/4/

关于javascript - Eloquent Javascript 中的练习 4.4 -- startsWith() 和 .slice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24223837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com