在 Javascript 中加入关联数组 [英] Join associative arrays in Javascript

查看:44
本文介绍了在 Javascript 中加入关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Javascript 中有两个(或更多)关联数组:

I have two (or more) associative arrays in Javascript:

tagArray['title'] = ('<H1>title</H1>');
tagArray['text'] = ('<P>text</P>');

并想加入他们,例如:

tagFinal = tagArray.join("<BR>");

但结果是空的.

它应该导致:tagFinal = '

title


text

It should result in: tagFinal = '<H1>title</H1><BR><P>text</P>';

我做错了什么?(我也试过没有标签,没有区别)还是我最好 push()-ng 到一个新的数组/字符串?

What am I doing wrong? (I also tried without the tags, no difference) Or am I better off push()-ng it to a new array/string?

推荐答案

JavaScript 中没有关联数组"类型这样的东西.有对象,也有数组.Array 原型有一个 .join() 方法,但 Object 没有.

There's no such thing as an "associative array" type in JavaScript. There are Objects and there are Arrays. The Array prototype has a .join() method, but Object does not.

(对象通常会做类似关联数组的工作,但没有内置的显式功能来模拟实际数组.例如,您也找不到对象实例的长度".)

(Objects in general do sort-of work like associative arrays, but there's no explicit functionality built in that mimics actual arrays. You can't find the "length" of an Object instance either, for example.)

你可以写这样一个函数:

You could write such a function however:

function smush( o, sep ) {
  var k, rv = null;
  for (k in o) {
    if (o.hasOwnProperty(k)) {
      if (rv !== null) rv += sep;
      rv += o[k];
    }
  }
  return rv;
}

您是否真的想将smush"函数限制为处理对象的直接属性(而不是继承的属性),以及是否要按类型过滤,这些都是您必须决定的为自己.

Whether you'd really want to limit the "smush" function to working on direct properties of an object (as opposed to inherited ones), and whether you might want to filter by type, are things you'd have to decide for yourself.

这篇关于在 Javascript 中加入关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆