rss

Javascript: Ways to iterate over an array

Category : General

for each in:

JAVASCRIPT:

  1. for each (var item in [1, 2, 3]) alert(item);

JavaScript 1.6 added the Array.forEach method:

JAVASCRIPT:

  1. [1, 2, 3].forEach(function(item) { alert(item) });

JavaScript 1.7 added array comprehensions for array initialization:

JAVASCRIPT:

  1. var squares = [item * item for each (item in [1, 2, 3])];

I just realized I can (ab)use comprehensions to iterate arrays with Perl-like syntax by throwing away the result:

JAVASCRIPT:

  1. [alert(item) for each (item in [1, 2, 3])];

I can iterate object properties the same way:

JAVASCRIPT:

  1. var obj = { foo: 1, bar: 2, baz: 3 };
  2. [alert(name + "=" + obj[name]) for (name in obj)];

Edward Lee points out how to use Iterators:

JAVASCRIPT:

  1. [alert(key + "=" + val) for ([key, val] in Iterator({a:1,b:2,c:3}))]
  • Share/Bookmark

Rails flash messages helper

2

Category : Ruby on Rails

display_flash(:error) # to display a specific flash message
display_flash # to display all flash messages

1
2
3
4
5
6
7
8
9
10
11
12
13
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
  FLASH_TYPES = [:error, :warning, :success, :message]
  def display_flash(type = nil)
    html = ""
    if type.nil?
      FLASH_TYPES.each { |name| html << display_flash(name) }
    else
      return flash[type].blank? ? "" : "#{flash[type]}"
    end
    html
  end
end
  • Share/Bookmark

Amit Yadav is Digg proof thanks to caching by WP Super Cache