简体   繁体   English

从另一个数组创建一个特定元素的数组?

[英]Create an array of specific elements from another array?

I have an array that can't be changed in terms of the element positions:我有一个在元素位置方面无法更改的数组:

var array = ['item1', 'section1', 'section2', 'section3', 'section4', 'section5', 'prod1', 'prod2']

I want to make a new array from 'array' that takes the elements from position 1 - 5 (so all the section elements).我想从“数组”创建一个新数组,该数组从 position 1 - 5 中获取元素(所以所有部分元素)。 It needs to be by position as the section elements make change by name.它需要由 position 作为部分元素按名称更改。

var array2=array.slice(1,6)

See here for more information.请参阅此处了解更多信息。

let's say we have an array like this假设我们有一个这样的数组

 const FILES_WITH_10_ASSETS = [
  '../assets/uploads/Desktop-300x600.jpeg',
  '../assets/uploads/Desktop-728x90.png',
  '../assets/uploads/Mobile-160x600.jpeg',
  '../assets/uploads/Mobile-300X50.jpeg',
  '../assets/uploads/Mobile-320x50.jpeg',
  '../assets/uploads/Mobile-320x480.jpeg',
  '../assets/uploads/Mobile-1024x768.jpeg',
  '../assets/uploads/Tablet-300x250.jpeg',
  '../assets/uploads/Tablet-Interstitial-320x480.gif',
  '../assets/uploads/Tablet-Interstitial-320x480.jpeg'
];

now we want some specific items from an array, we will create a function for this, here I have stored the function in an constant for further use现在我们想要一个数组中的一些特定项目,我们将为此创建一个 function,这里我将 function 存储在一个常量中以供进一步使用

const SELECT_ASSETS = function(assetName: string) {
  let filtered_assets: string[] = [];
  for (let i in FILES_WITH_10_ASSETS) {
    if (FILES_WITH_10_ASSETS[i].includes(assetName) === true) {
      filtered_assets.push(FILES_WITH_10_ASSETS[i]);
    }
  }
  return filtered_assets;
};

and we call the method like this in our file我们在我们的文件中调用这样的方法

const ASSETS_NAME = SELECT_ASSETS(ASSET_NAME);

now we can pass the assets name to any function or method, if we pass the ASSET_NAME as Tablet we will get all three tablet paths, or if we change it to Mobile, we will get all five Mobile paths现在我们可以将资产名称传递给任何 function 或方法,如果我们将 ASSET_NAME 作为平板电脑传递,我们将获得所有三个平板电脑路径,或者如果我们将其更改为移动设备,我们将获得所有五个移动设备路径

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM