2017-01-15 5 views
8

Я пишу функцию сокращения, где в любое время я нажимаю кнопку, мне нужно добавить число n в четвертый элемент массива. Если элемент L или M я не хочу добавленияМетод массива для циклирования для каждого элемента

Примера У меня есть этот массив ниже, и номер для добавления, т.е. n является «5»

[M 175 0 L 326 87 L 326] 

я нажимаю кнопку один раз и массив становится

[M 175 0 L 331 87 L 326] 

Четвертый элемент становится 331

я нажимаю кнопку дважды, а массив становится

[M 175 0 L 331 92 L 326] 

Пятый элемент становится 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); 

here См в действии

, но теперь я нужен другой метод массива, чтобы достичь этого, но я не знаю, кто и как

+4

Пожалуйста, не используйте 'string' как переменную, ее легко спутать с глобальной' String'. – Gerrit0

+0

Это всегда первый и второй элемент после первого 'L'? –

+0

добавьте, какой элемент вы хотите изменить и как выглядит строка ввода и желаемый вывод. и что означает * «И так далее, пока массив не закончится, и я снова начну с третьего элемента» *? только '' L''part/s? –

ответ

1

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'));
<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>

Позвольте мне знать, если у вас есть какие-либо вопросы .. просто дать линию, и я объясним

+0

Я согласен с ответом, но если вы можете показать, как это делается в моем сценарии для меня, это яснее. Я покажу вам здесь https://gist.github.com/Mannaio/35f50c0ecc71f6e35ca6f918fadec492 – Koala7

+0

Ответ Sagar Shetty показывает метод массива, который мне нужен, но он не достигает результата, который я хочу. Этот ответ, если он изменен, поскольку ваша демонстрация является правильной – Koala7

0

Я предлагаю вам решение в чистых JS без реакции

var string = "M 175 0 L 326 87 L 326 262 M 175 350 L 23 262 L 23 87 M 175 0"; 
 
var array = string.split(" "); 
 
var max = array.length; 
 
var i = 3; 
 
var clic =() => { 
 
     i++; 
 
     if (i === max) i = 3; 
 
     if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 5; 
 
     console.log(array.join(' ')); 
 
}; 
 
clic(); clic(); clic(); clic(); clic(); clic(); 
 
clic(); clic(); clic(); clic(); clic(); clic(); 
 
clic(); clic(); clic(); clic(); clic(); clic(); 
 
clic(); clic(); clic(); clic(); clic(); clic();

1

В то время как not.act.js, но чистый JS, вы можете сделать следующее:

function ClickHandler(s){ 
 
    this.cct = 3; // click count 
 
    this.str = s; // the string 
 
    this.num = 5; // increase amount 
 
    this.but = null; // the add button element 
 
    this.res = null; // the result paragraph element 
 
} 
 
ClickHandler.prototype.insert = function(){ 
 
    var a = this.str.split(/\s+/); 
 
    this.str = a[this.cct] === "L" || a[this.cct] === "M" ? a.join(" ") 
 
                 : (a[this.cct] = (+a[this.cct] + this.num) + "", a.join(" ")); 
 
    this.cct = (this.cct+1)%a.length || 3; 
 
}; 
 
ClickHandler.prototype.increase = function(){ 
 
    this.but.textContent = this.but.textContent.replace(/-?\d+/,++this.num); 
 
}; 
 
ClickHandler.prototype.decrease = function(){ 
 
    this.but.textContent = this.but.textContent.replace(/-?\d+/,--this.num); 
 
}; 
 

 
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", 
 
whenClicked = new ClickHandler(string), 
 
    increase = document.getElementById("increase"), 
 
    decrease = document.getElementById("decrease"); 
 

 
whenClicked.but = document.getElementById("myButton"); 
 
whenClicked.res = document.getElementById("result"); 
 
whenClicked.res.textContent = string; 
 
whenClicked.but.addEventListener("click", function(e){ 
 
              this.insert(); 
 
              this.res.textContent = this.str; 
 
              }.bind(whenClicked)); 
 
increase.addEventListener("click", whenClicked.increase.bind(whenClicked)); 
 
decrease.addEventListener("click", whenClicked.decrease.bind(whenClicked));
<button id="myButton">Add 5</button> 
 
<p id="result"></p> 
 
<button id="increase">Increase</button> 
 
<button id="decrease">Decrease</button>

1

Ваша проблема, если я правильно понимаю, из существующего массива, получить один (не обязательно новый), а следующее правило:

If the current value is M or L do nothing, return the value, else 
consider it a number, add 5 to it and return. 

Рассмотрим в implemation :

function getValue (original, value) { 

    return original === "M" || original === "L" ? original : parseFloat(original, 10) + value; 

} 

So everyti я запускаю ваш обработчик, вы можете обновить свой массив, присоединить его к пробелу и отобразить SVG (я полагаю, это путь).

Что-то вдоль этих линий:

const array = // your array 
const index = 5; 
function onClick() { // you need to attach this handler to whatever node/object you are listening to 

    array[index] = getValue(array[index], 5); 

} 

Если вы используете React, вы можете вызвать засавить. Ваш компонент будет выглядеть как-то вроде этого:

class C extends React.Component { 

    constructor (props) { 

     super(props); 
     this.state = { array: .... } // the state is initialized with your array 


    } 


    render() { 

     return <div> 
      {/*anything you want*/} 
      <button onClick={() => this.setState({ 

       array: [...this.state.array.slice(4), getValue(this.state.array[4], 5), ...this.state.array.slice(5)] 
      })}>Click me</button> 
     </div>; 

    } 

} 
1

Вы можете использовать Array.prototype.reduce() (Refer)

Уменьш() метод применяет функцию от аккумулятора и каждого значения массива (слева направо), чтобы уменьшить его до одного значения.

var str = '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'; 

str.split(/\s+/).reduce((prevVal, x) => x === 'M' || x === 'L' ? prevVal + ' ' + x : prevVal + ' ' + (+x + 5)); 

Так уменьшить ваш другой метод, который вы можете использовать.

+0

, это метод массива, который мне нужен, но единственная проблема здесь заключается в том, что суммируем 5 ко всем числам в любое время, когда я нажимаю, мне нужно суммировать '5' от четвертого элемента и только к числу i. См. Демо-версию Abdennour TOUMI – Koala7

0

Используйте это:

let string = state[a].d 
let array = string.split(/\s+/) 
var n=5; 
var finalArray=array.map(function(current, index) { 
    if (current=="L" || current=="M") { 
    return current; 
    }else{ 
    return new Number(current)+n*4-n*(3-Math.min(index,3)); 
    } 

}); 

Это дает окончательный массив, который вы получите после запуска через процесс полностью из индекса 3 (элемент 4) до 0.

Смежные вопросы