【发布时间】:2022-10-14 16:43:27
【问题描述】:
我有一个关于 JavaScript 算法的简单问题
https://www.codewars.com/kata/56747fd5cb988479af000028/train/javascript
我正在解决这个问题。这个问题的解释是从奇数字符中间提取两个字母
我很好奇的是
function getMiddle(s) {
//Code goes here!
let answer = "";
if (s.length % 2 !== 0) {
answer += s[Math.floor(s.length / 2)];
} } else {
answer += s.slice(
(Math.floor(s.length / 2 - 1), Math.floor(s.length / 2 + 1))
);
}
return answer;
}
console.log(getMiddle("test"));
console.log(
"test".slice(
Math.floor("test".length / 2 - 1),
Math.floor("test".length / 2 + 1)
)
);
getMiddle函数的返回值到底和console.log('test'.slice~')有区别吗?
不同的是,一个是函数的返回值,一个是直接从控制台取的,但是不知道为什么是一样的代码,但是值不同crying
请帮我
【问题讨论】:
-
你有一些不匹配的花括号。请确保代码是minimal reproducible example?
-
正确缩进代码是一个好习惯。更容易看到它在做什么(也为你),并调试它。
标签: javascript