根据数组的长度更改数组的每个元素的最佳方法是什么?
Ví dụ:
User #1 input = "XYZVC"
Expected Output = "BLABL"
User #2 input = "XYZVCAD"
Expected Output = "BLABLAB"
我希望B
替换index[0]
,L
替换index[1]
,以及A
替换 index[2]
。如果用户输入长于 3,我最费劲的部分也是让它重复。
nỗ lực của tôi
我试图将输入split()
到一个数组中,shift()
并将它push()
到一个新的数组没有任何运气。
我已将我的代码粘贴到下面以获得更多详细信息:
import React from 'react'
class UserInput extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
}
handleChange = (event) => {
this.setState({value: event.target.value})
}
handleSubmit = (event) => {
alert('Your input has been submitted: ' + this.state.value)
event.preventDefault()
}
badRobot = () => {
//Check length of user input
//Add B, L, A, matching the length of the user input
//Store it within a new variable
//Plug that into the bad robots output
let checkedInput = this.state.value
let checkedArray = checkedInput.split('')
const newArr = checkedInput.shift()
}
render(){
return(
)
}
}
export default UserInput
gia hạn
事实证明,有一个字符串函数,padStart (也适用于 padEnd)这将非常容易地做到这一点:
const input1 = "XYZVCAD"
const input2 = "erkjguherkluagheruhg"
function mask(str){
return ''.padStart(str.length, 'BLA');
}
console.log(mask(input1))
console.log(mask(input2))
实现它的一种方法是使用 repeat
函数,然后根据原始字符串长度剪切字符串:
const input1 = "XYZVCAD"
const input2 = "erkjguherkluagheruhg"
function mask(str){
return 'BLA'.repeat(str.length / 3 + 1).substring(0, str.length)
}
console.log(mask(input1))
console.log(mask(input2))
repeat
函数将重复您的字符串 x
次,您将在上面链接的文档中看到。在这里,由于您的字符串长度为 3 个字符,我们只需要根据原始字符串的长度除以 3 来重复您的字符串。我添加一个,因为像 5/3
这样的除法将是四舍五入为 1
,导致 BLA
,即使您的字符串更长。
最后一步,substring
,会将您的字符串简单地剪切成与原始字符串完全相同的长度。
这是实现它的另一种方法,通过将字符串拆分为数组,并使用模数运算符为其提供正确的字母:
const input1 = "XYZVCAD"
const input2 = "erkjguherkluagheruhg"
function mask(str){
return str.split('').map((ch, index) => 'BLA'[index % 3]).join('')
}
console.log(mask(input1))
console.log(mask(input2))
Tôi là một lập trình viên xuất sắc, rất giỏi!