2017-12-15 10 views
0

サイトからデータを取り出して変数に格納しています。次に、ボタンをクリックするたびにそのオブジェクトから3つのプロパティを返すforループを実行しています。その部分は完璧に動作しています。JavaScriptを使ってforループを使用してオブジェクトから次の3つのアイテムを取得する方法はありますか?

ただし、ボタンをクリックするたびに全く同じデータが返されます。特定のオブジェクトからforループを開始する方法がわかりません。

data: { 
    fetched_list: [], // the object containing the data fetched when called 
    list: [],   // an empty list that will contain future pushed object 
    list_key: '0'  // the last loop index 
}, 

requestInformation(){ 
    const temp = []; 
    for (let i = 0; i < 3; i++){ 
    temp.push(this.fetched_list[i]); 
    } 
    this.list = this.list.concat(temp); // here we push the fetched data to the list 
} 

この時点で、ボタンをクリックするたびに次の3つのオブジェクトでforループを開始する方法がわかりません。

最後にiの数値をlist_keyに保存しようとしていましたが、次の3つのプロパティを取得する方法を知りません。あなたはthis.recipe.list_keyインクリメント

答えて

1

変更が必要なものがいくつかあります。ここで

は実施例である:https://jsfiddle.net/auq7wzuc/6/

基本的には、次の行:

this.recipe.list_key = this.recipe.list_key++; 

は、それは常にゼロになりますvalue--をインクリメントすることはありません。私たちは3ずつ増加したいので、使用する必要があります。

this.recipe.list_key += 3; 

はまた、我々はループのための条件を変更する必要があるので、代わりに3で停止するのではなく、開始より3以上で停止します。

+0

はい、それは今より多くの意味があります。 – Craig

1

https://jsfiddle.net/auq7wzuc/が道で間違いに気づき、forループ内i < 3のあなたの比較:

私は正確にここでの問題を再現しました。私はそれを動作させるように修正しました。以下のコードを見てください。これがあなたが必要としていることを願っています。

私はまた、CHARからlist_key初期値を変更する自由を取った「0」(加算問題対JavaScriptの連結を処理するために)0をintに

new Vue({ 
    el: '#app', 
    data: { 
     recipe: { 
      fetched_list: [], 
     list: [], 
      list_key: 0 
     } 
    }, 
    methods: { 
    requestInformation(){ 
     const temp = []; 
     console.log(this.recipe.list_key); 
     var end = this.recipe.list_key + 3; 
     for (let i = this.recipe.list_key; i < end ; i++){ 
     temp.push(this.recipe.fetched_list[i]); 
     } 
     this.recipe.list_key += 3; 
     this.recipe.list = this.recipe.list.concat(temp); 
    } 
    }, 
    created(){ 
     axios.get('https://hn.algolia.com/api/v1/search_by_date?tags=story').then(({data}) => this.recipe.fetched_list = data.hits); 
    } 
}); 

疑問/明確化を歓迎します。

1
data: { 
    recipe: { 
     fetched_list: [], 
    list: [], 
     list_key: 0 
    } 
}, 
methods: { 
requestInformation() { 
    this.recipe.list = this.recipe.fetched_list 
    .slice(0, this.recipe.list_key += 2) 
    .map(item => item); 
} 
} 
関連する問題