【问题标题】:JSON array splitting React JSJSON 数组拆分 React JS
【发布时间】:2022-01-23 22:29:58
【问题描述】:

我的状态中有一个 JSON 数组,我想使用它的另一半。例如,如果 JSON 数组的大小为 10,我有兴趣访问后面的 5 个值。我怎样才能做到这一点?我尝试了很多解决方案,但我总是会出错。 我正在使用 React JS。 所以我正在使用地图功能,但我无法满足我的条件。

  data.map((item, index) => {

我无法使用 reduce 或 filter 我也试过了。

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

正如@SaeedShamloo 提到的slice 方法在这里就足够了

data.slice(Math.floor(data.length/2), data.length).map(item => )

【讨论】:

  • data.form.slice(Math.floor(0), data.form.length/2).map((item, index) => { }) 如果这样做是正确的吗我要访问前半部分?
  • 操作问题是For example if the size of the JSON array is 10, I am interested in to access the later 5 values
【解决方案2】:

通过数组索引使用filter。

const data = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15];

const res = data.filter((_, idx, arr) => idx >= arr.length / 2);

console.log(res);


// Alternatively
const res2 = data.slice(-data.length/2);

console.log(res2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2012-01-01
    相关资源
    最近更新 更多