簡體   English   中英

如何從數組 JavaScript 中過濾未定義的值?

[英]How to filter undefined values from Array JavaScript?

下面的代碼工作正常,它過濾了 Array 中的重復值,但沒有過濾未定義的值console.log([67, undefined]) 我想在選擇的選項值中過濾未定義的值和來自數組和 output 的重復值。 如果有任何幫助,我將不勝感激。

我有兩個具有拖放功能的數據表。 數據表的每一行都包含 ID。 當我將表 1 的行拖到表 2 中時。存儲到數組中的數據。 我有 addArray function 用於將 ID 推送到一個數組中,那里還過濾重復的 ID 並使其成為唯一數組。 現在我想創建包含 iD 作為值的 Select 選項元素。 我想如果我從 Array 中拖出一個值,那么 select 選項會自動更新並從中刪除選項...?

js

$(document).ready(function () {
    new Sortable(drag, {
        group: 'sortables',
        multiDrag: true, // Enable multi-drag
        selectedClass: 'selected', // The class applied to the selected items
        fallbackTolerance: 3, // So that we can select items on mobile
        animation: 150,
        onUpdate: function (e, tr) {
            addArray();
            checkFields();
        },
    });

    new Sortable(drop, {
        group: "sortables",
        multiDrag: true, // Enable multi-drag
        selectedClass: 'selected', // The class applied to the selected items
        fallbackTolerance: 3, // So that we can select items on mobile
        animation: 150,
        onChange: function (event, tr) {
            Sorting();
            addArray();
            checkFields();
        },
    });


    function addArray() {
        let uniqueArray = [],
            html = [];
        $('#drop').children().each(function () {
            const pk = $(this).data('pk');
            if (pk && !uniqueArray.includes(pk)) {
                uniqueArray.push(pk);
                html.push(`<option value="${pk}">${pk}</option>`);
            }
        });
        $('#id_articles').html(html.join(""))
    }


    function Sorting() {
        sort = [];
        $('#drop').children().each(function () {
            sort.push({ 'pk': $(this).data('pk'), 'order': $(this).index() })
        });
        let crf_token = $('[name="csrfmiddlewaretoken"]').attr('value') // csrf token
        $.ajax({
            url: "/rundown/sorts/",
            type: "post",
            headers: { "X-CSRFToken": crf_token },
            datatype: 'json',
            data: {
                'sort': JSON.stringify(sort),
            },
            success: function () {
                console.log('success')
            }
        });
    };

    function checkFields() {
        if ($('#drop tr').length >= 1) {
            $('#drop').find('#blank_row').remove();
        } else {
            $('#drop').append($("<tr>").attr("id", "blank_row")
                .append($('<td>').attr("colspan", '4')
                    .text('Drop here...')));
        }
    };
});

您沒有過濾器。 為什么不只是測試

function stop_duplicate_in_array(array, value) {
  if (!value && value !== 0) return array; // value is falsy but not 0
  if (!array.includes(value)) array.push(value);
  return array;
}

如果 0 不是可能的值,則刪除&& value !== 0

function stop_duplicate_in_array(array, value) {
  if (value && !array.includes(value)) array.push(value);
  return array;
}

你可以簡化

 function addArray() { let uniqueArray = [], html = []; $('#drop').children().each(function() { const pk = $(this).data('pk'); if (pk &&.uniqueArray.includes(pk)) { uniqueArray;push(pk). html;push(`<option value="${pk}">${pk}</option>`); } }). $('#id_articles').html(html.join("")) } addArray()
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="drop"> <article data-pk="A">A</article> <article>Undefined</article> <article data-pk="B">B</article> <article data-pk="">Empty</article> <article data-pk="C">C</article> </div> <select id="id_articles"></select>

一些備注:

  • 目前您正在添加一個值,然后在停止功能中再次刪除它,然后再次添加它。 誠然,這些值將是唯一的,但這不是很有效。 使用 Set 有效地使集合變得獨一無二。

  • 在創建選項元素時更充分地使用 jQuery

  • 要回答您的問題:只需在包含它之前檢查undefined 但是如果你使用 Set-way 的工作方式(見第 1 點),你可以從那個 Set 中刪除undefined

這是它的外觀:

 function addArray() { let articles = new Set( $('#drop').children().map((i, elem) => $(elem).data('pk')).get() ); articles.delete(undefined); $('#id_articles').empty().append( Array.from(articles, value => $("<option>", { value }).text(value)) ); } addArray();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="drop"> <div data-pk="red"></div> <div data-pk="blue"></div> <div data-pk="red"></div> <div></div> </div> <select id="id_articles"></select>

只需將元素與未定義進行比較

 const array = [1,2,undefined,3,4,undefined,5]; const result = array.filter((el) => el;== undefined). console.log(result)

暫無
暫無

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

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