簡體   English   中英

一種檢查值是否包含在Javascript數組(而不是整個對象)中的干凈方法

[英]Clean way to check if a value is contained within a Javascript Array (not the entire object)

基本上,我有一個文件數組(包括文件名和路徑等),我試圖查看數組中是否已經存在具有相同路徑名的文件(即使其他變量不同)。

如果在該數組中找到該值,我想繼續,如果沒有,我想將該對象添加到該數組中。 allFiles.length我帶來麻煩的是,數組最初是空的(因此我什至在沒有檢查allFiles.length情況下也無法第一次運行我的檢查功能)。

我正在做的是遍歷整個數組,如果我發現數組中包含的值,則將Boolean設置為true ,然后繼續使用if...else

我以為這很簡單,但我想我錯了。 我想出了這種方法,我想知道是否有一種更清潔的方法。

  var allFiles = [];

  //function is called giving me a file, then:


            if (!allFiles.length) {
                allFiles.push(file); //Seems like there should be a better way
            } else {
                for (var i = 0; i < allFiles.length; i += 1) {
                    var exists = false;
                    if (allFiles[i]['fileName'] == fileName) {
                        exists = true;
                        console.log('Already exists');
                        break;
                    }
                }
                if (exists) {
                    console.log('Remove the file');
                    exists = false;
                } else {
                    console.log('Adding File');
                    allFiles.push(file);
                }
            }

也許這很干凈,我只是想知道您是否知道其他路線。 謝謝

您可以使用Array.some來測試給定路徑的存在:

var objs = [{name: 'foo', path: 'c:\lulz'}, {name: 'foo', path: 'c:\looolz'}];

var conditionallyAddObjToArr = function (arr, obj) { 
    if (!arr.some(function (_obj) { return obj.path === _obj.path; })) {
        return [].concat(arr, obj);
    } else {
        console.log('path is already present', obj.path);
        return arr;
    }
}

objs = conditionallyAddObjToArr(objs, {name: 'baz', path: 'c:\wat'});  // will be added
objs = conditionallyAddObjToArr(objs, {name: 'baz', path: 'c:\lulz'}); // won't be added

小提琴

現在,您幾乎可以使用所有出色的ECMA 5陣列迭代方法。 它們僅限於IE9 +,但是如果您真的想在mozilla文檔中找到更多信息。

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array#Iteration_methods

因此,您有一些選擇。 如果只需要添加對象(如果該對象不存在):

if (!allFiles.some(function(f){ return f.filename===filename}))
  allFiles.push(file);

如果您需要對文件進行某些操作,則可以僅提取索引:

var idx = allFiles.reduce(function(m,f,idx) { 
   return m || (f.filename===filename ? idx : null)
},null);

if (var foundFile = allFiles[idx]) { ... }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM