Skip to content

js compiler: jsified array cannot be used with for...in in the javascript world #43911

Open
@alextekartik

Description

@alextekartik

While trying to wrap a 3rd party library on node js (so using node_compilers) that was using for...in to iterate through arrays (maybe bad but I cannot control that), I encountered a weird behavior. jsified array cannot be iterated safely using for...in.

Consider the following javascript code:

function testArrayJoinJs() {
  const elements = ['Fire', 'Air', 'Water'];
  return testArrayJoin(elements);
}

function testForInArrayJoinJs() {
  const elements = ['Fire', 'Air', 'Water'];
  return testForInArrayJoin(elements);
}

function testArrayJoin(array) {
  return array.join(',');
}

function testForInArrayJoin(array) {
  // Use for in to build a new array
  var newArray = [];
  for (var key in array) {
    newArray.push(array[key]);
  }
  return newArray.join(',');
}

And the following dart test:

test('forInJs', () {
  const elements = ['Fire', 'Air', 'Water'];
  var expected = elements.join(',');
  expect(testArrayJoinJs(), expected);
  expect(testForInArrayJoinJs(), expected);
  expect(testArrayJoin(elements), expected);
  expect(testForInArrayJoin(elements), expected); // Error !?!
});

When ran using:

dart test -p chrome

or

 dart pub run build_runner test -- -p chrome

The last test is failing with the error:

Expected: 'Fire,Air,Water'
  Actual: 'Fire,Air,Water,function Array() { [native code] },function Array() { [native code] }'
   Which: is different. Both strings start the same, but the actual value also has the following trailing characters: ,function  ...

It seems like 80 keys are added to the array on the javascript side. The issue is available here:

https://github.com/tekartik/browser_utils.dart/blob/f799d8f1df191fadfb40bca98f7ca342eae98a75/test/js_utils_browser_test.dart#L237-L251

Reproduced on Dart 2.10.2 stable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-web-jsIssues related to JavaScript support for Dart Web, including DDC, dart2js, and JS interop.type-questionA question about expected behavior or functionalityweb-js-interopIssues that impact all js interopweb-triage-0repro is available

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions