gpt4 book ai didi

javascript - 给定一个字符串,将每个单词的第一个字母移动到每个单词的末尾,然后将 "ay"添加到每个单词的末尾并返回一个新字符串 - JavaScript

转载 作者:行者123 更新时间:2023-11-28 12:13:28 24 4
gpt4 key购买 nike

到目前为止我已经:

function pigIt(str) {

//split string into array of words
let words = str.split(" ");

//loop through array of words
for (let i = 0; i < words.length; i++) {

//loop through individual words
for (let j = 0; j < words.length; j++) {

//get first word in words
let firstWord = words[0];

//get first character in first word
let firstChar = firstWord[0];

//Create new word without first character
let unshiftedWord = firstWord.unshift(0);

//move first character to the end
let newWord = unshiftedWord.push(firstChar) + "ay";

return newWord;

}
}
}

console.log(pigIt('Pig latin is cool'));

现在,我只想返回“igPay”。然后,我将把这些字符串组合在一起形成一个新字符串。

但它不喜欢firstWord.unshift(0);。它说:

TypeError: firstWord.unshift is not a function.

但是.unshift() is a function ?为什么这不起作用?

一旦我得到一个新单词,我应该能够将 newWords 组合在一起形成 newString,尽管可能有比创建新单词更有效的方法-为每个单独的单词循环。

https://www.codewars.com/kata/520b9d2ad5c005041100000f/train/javascript

编辑:我希望使用传统函数声明而不是箭头符号来编写此函数。

编辑2实现@Ori Drori的代码后,我的函数如下所示:

function pigIt(str) { 

newString = str.replace(/(\S)(\S+)/g, '$2$1ay');
return newString;
}

console.log(pigIt('Pig latin is cool'));

它有效 - 但我不明白 str.replace(/(\S)(\S+)/g, '$2$1ay'); 到底在做什么。

最佳答案

更简单的方法是使用 map()join()

注意:根据 codewars 示例,只有 ay 被添加到包含 aplhabets 的字符串,而不是 !。因此,您应该使用 test() 测试数组的元素是否为 aplhabet。

以下解决方案通过了 codewars 中的所有测试。

function pigIt(str){
return str.split(' ').map(x =>/[a-zA-Z]+/.test(x) ? x.slice(1)+x[0]+'ay' : x).join(' ');
}
console.log(pigIt('Pig latin is cool'));

没有箭头功能。

function pigIt(str){
return str.split(' ').map(function(x){
return /[a-zA-Z]+/.test(x) ? x.slice(1)+x[0]+'ay' : x;
}).join(' ');
}
console.log(pigIt('Pig latin is cool'));

简单的for循环

这是使用简单的 for 循环的代码

function pigIt(str){
str = str.split(' ');
for(let i = 0;i<str.length;i++){
if(/[a-zA-Z]/.test(str[i])){
str[i] = str[i].slice(1) + str[i][0] + 'ay';
}

}
return str.join(' ');
}
console.log(pigIt('Pig latin is cool'));

关于javascript - 给定一个字符串,将每个单词的第一个字母移动到每个单词的末尾,然后将 "ay"添加到每个单词的末尾并返回一个新字符串 - JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55501660/

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