Koa*_*la7 8 javascript arrays for-loop reactjs redux
我正在写一个redux函数,任何时候我点击一个按钮我必须n在数组的第四个元素添加一个数字.如果元素是L或M,我不想添加
示例我在下面有这个数组,并且要添加的数字,即n'5'
[M 175 0 L 326 87 L 326]
Run Code Online (Sandbox Code Playgroud)
我单击按钮一次,阵列变为
[M 175 0 L 331 87 L 326]
Run Code Online (Sandbox Code Playgroud)
第四个元素变成了 331
我单击按钮两次,数组变为
[M 175 0 L 331 92 L 326]
Run Code Online (Sandbox Code Playgroud)
第五个元素变成了 92
依此类推,直到阵列结束,我再次从第三个元素开始
这是我的初始函数,我在其中映射所有值
var string = 'M 175 0 L 326.55444566227675 87.50000000000001 L 326.55444566227675 262.5 L 175 350 L 23.445554337723223 262.5 L 23.44555433772325 87.49999999999999 L 175 0',
array = string.split(/\s+/),
result = array.map(x => x === 'M' || x === 'L' ? x : +x + 5).join(' ');
console.log(result);
Run Code Online (Sandbox Code Playgroud)
看到这里的行动
但现在我需要一个其他数组方法来实现,但我不知道哪个以及如何
let clicks = 0;
class App extends React.Component {
state= {data:'M 175 0 L 326 87 L 326'};
onClick() {
clicks ++;
this.setState({data: this.increment()});
}
/**
* clicks -> Element index in array
* 1 ----- ->4,
* 2 ---- -> 5.
* 3 ---- -> 7.
* 4 ----- ->4,
* 5 ---- -> 5.
* 6 ---- -> 7.
*/
increment() {
const data = this.state.data.replace(/\ \ /g, " ").split(" ");
const indexAlteredElement = (clicksModulo) => (! clicksModulo % 3) ? 7 : clicksModulo+3;
return data.map((e, i) => (i === indexAlteredElement(clicks%3)) ? parseInt(e)+5 : e ).join(' ')
}
render() {
return (
<div>
<div>{this.state.data} </div>
<button onClick={this.onClick.bind(this)} style={{fontSize:20}}> Click me </button>
</div>
)
}
}
ReactDOM.render(<App />, document.querySelector('.container'));Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<section class="container"></section>Run Code Online (Sandbox Code Playgroud)
如果您有任何问题,请告诉我..只需给出该行,我会解释
| 归档时间: |
|
| 查看次数: |
563 次 |
| 最近记录: |